import { _decorator, Component, EventTouch, Node, UITransform } from 'cc';
import { Player } from './tank/Player';
import { myGame } from './MyGame';
const { ccclass, property } = _decorator;

@ccclass('Hocker')
export class Hocker extends Component {
    public nodeDown: Node = null
    public nodeUp: Node = null
    public nodeLeft: Node = null
    public nodeRight: Node = null

    onLoad() {
        this.nodeDown = this.node.getChildByName('Down')
        this.nodeUp = this.node.getChildByName('Up')
        this.nodeLeft = this.node.getChildByName('Left')
        this.nodeRight = this.node.getChildByName('Right')
    }

    onEnable() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
    }

    onDisable() {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this)
    }

    onTouchStart(evt: EventTouch) {
        this.setPlayerDirection(evt)
    }

    onTouchMove(evt: EventTouch) {
        this.setPlayerDirection(evt)
    }

    onTouchEnd() {
        myGame.player.stopMove()
    }

    onTouchCancel() {
        myGame.player.stopMove()
    }

    setPlayerDirection(evt: EventTouch) {
        const location = evt.getUILocation()
        const arr = [this.nodeLeft, this.nodeRight, this.nodeUp, this.nodeDown]
        const index = arr.findIndex((node) => {
            return node.getComponent(UITransform).getBoundingBoxToWorld().contains(location)
        })

        if (index != -1) {
            myGame.player.setDirection(index)
        }
        else {
            myGame.player.stopMove()
        }
    }
}


